package com.qidian.common.beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.qidian.common.Constants;
import com.qidian.common.MessageStatus;
import com.qidian.common.TableMeta;

public class MessageBean implements ISyncBean
{
	static Logger logger = Logger.getLogger(MessageBean.class) ;
    // 消息ID
    Long id = -1L;
    // 账户ID
    Long accountId = -1L;
    // 主账号ID
    Long userId = -1L;
    // 回答的客户端ID;
    Long clientId = -1L;
    
    // 消息来源IP地址
    String ip = null;
    // 消息来源端口
    int port = -1;
    // 超时时间
    int interval = -1;
    // 接收时间
    long receiveTime = -1L;
    // 客户端回答时间
    long answerTime = -1L;
//    // 服务器应答时间
//    long responseTime = -1;
    // 客户端取题时间
	long requestTime = -1;
    //图片（或其他媒体文件）的相对路径
    String relativePath = null;
    // 消息的状态
    volatile int status = 0;
    // 答案
    volatile String answer = null;
    // 项目类型
    int gameType = -1;
    // 内容
    byte[] content = null;
    // 内容类型
    String contentType = null;
    
    // 用户自定义扣除点数(一般等于项目类型的点数，分成模式下可能比该值较大)
    int uPoint ;
    // 返点账号ID
    long returnUserId ;

    
    public final static String clearSQLPrefix = "delete from " + TableMeta.table_message + " where " + TableMeta.column_receive_time + " < " ;
    
    
	public long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public long getAccountId() {
		return accountId;
	}
	public void setAccountId(Long accountId) {
		this.accountId = accountId;
	}
	public long getClientId() {
		return clientId;
	}
	public void setClientId(Long clientId) {
		this.clientId = clientId;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public int getInterval() {
		return interval;
	}
	public void setInterval(int interval) {
		this.interval = interval;
	}
	public long getReceiveTime() {
		return receiveTime;
	}
	public void setReceiveTime(long receiveTime) {
		this.receiveTime = receiveTime;
	}
	public long getAnswerTime() {
		return answerTime;
	}
	public void setAnswerTime(long answerTime) {
		this.answerTime = answerTime;
	}
	public long getRequestTime() {
		return requestTime;
	}
	public void setRequestTime(long requestTime) {
		this.requestTime = requestTime;
	}
	public String getRelativePath() {
		return relativePath;
	}
	public void setRelativePath(String relativePath) {
		this.relativePath = relativePath;
	}
	public int getStatus() {
		return status;
	}
	private String getMessageStatus(int status)
	{
		return MessageStatus.values()[status].description;
	}
	public String getMessageStatus()
	{
		return MessageStatus.values()[status].description;
	}
	
	public void setStatus(int status) {
		if (this.status <= status)
			this.status = status;
		else
		{
			System.err.println("状态设置异常:"+id+getMessageStatus(this.status)+"-->"+getMessageStatus(status));
			logger.error("状态设置异常:"+id+getMessageStatus(this.status)+"-->"+getMessageStatus(status)) ;
		}
	}
	public String getAnswer() {
		return answer;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}
	public int getGameType() {
		return gameType;
	}
	public void setGameType(int gameType) {
		this.gameType = gameType;
	}
	public String toString()
	{
		StringBuffer sb = new StringBuffer() ;
		sb.append("ID:").append(this.id).append(";") ;
		sb.append("answerTime:").append(this.answerTime).append(";") ;
		sb.append("GameType:").append(this.gameType).append(";") ;
		sb.append("interval:").append(this.interval).append(";") ;
		sb.append("port:").append(this.port).append(";") ;
		sb.append("receiveTime:").append(this.receiveTime).append(";") ;
//		sb.append("responseTime:").append(this.responseTime).append(";") ;
		sb.append("requestTime:").append(this.requestTime).append(";") ;
		sb.append("status:").append(this.status).append(";") ;
		sb.append("answer:").append(this.answer).append(";") ;
		sb.append("clientId:").append(this.clientId).append(";") ;
		sb.append("accountId:").append(this.accountId).append(";") ;
		sb.append("ip:").append(this.ip).append(";") ;
		sb.append("relativePath:").append(this.relativePath).append(";") ;
		
		return sb.toString() ;
	}
	
	@Override
	public boolean setParameters(PreparedStatement ps) 
	{
		try 
		{		
			ps.setLong(1, id) ;
			ps.setLong(2, accountId) ;
			ps.setLong(3, clientId) ;
			ps.setString(4, ip) ;
			ps.setInt(5, port) ;
			ps.setInt(6, interval) ;
			ps.setLong(7, receiveTime) ;
			ps.setLong(8, answerTime) ;
			ps.setLong(9, requestTime) ;
			ps.setString(10, relativePath) ;
			ps.setInt(11, status) ;
			ps.setString(12,answer) ;
			ps.setInt(13, gameType) ;
			ps.setObject(14, content) ;
			ps.setString(15, contentType) ;
			ps.setLong(16, userId) ;
			ps.setInt(17, uPoint) ;
			ps.setLong(18, returnUserId) ;
			
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
			logger.error(e.getMessage()) ;
			return false ;
		}
		return true ;
	}
	
	/**
	 * 只存储超时题、错题
	 * 
	 * */
	@Override
	public boolean needSynchronized() 
	{
//		//已应答消息，且未超时，则不同步
//		if ((status == MessageStatus.ANSWERED.status || status == MessageStatus.RESPONSED.status) 
//				&& !isTimeOut())
//			return false ;
		
		// 对于正确消息,清空对象内容
		if (status == MessageStatus.ANSWERED.status && 
				(answer != null && answer.length() > 0))
			content = null ;
		
		return true;
	}
	
	/**
	 * 是否回答正确
	 * 
	 * */
	public boolean isCorrentMsg()
	{
		return status == MessageStatus.ANSWERED.status ;
	}
	
	/**
	 * 消息是否超时，
	 * 	已经回答：回答时间与接收时间的间隔大于超时时间;
	 * 	未回答：现在时间与接收时间的间隔大于超时时间.
	 * 
	 * */
	public boolean isTimeOut()
	{
		if (answerTime > 0 && answerTime - receiveTime > interval*1000)
			return true ;
		
	    if (answerTime <= 0 && System.currentTimeMillis() - receiveTime > interval*1000)
	    	return true ;
	    
	    return false ;
	}
	
	public void setTimeOut()
	{
		setStatus(MessageStatus.TIME_OUT.status) ;
	}
	
	/**
	 * 是否到达同步时间：超过消息的接收时间3分钟(200秒)；
	 * 
	 * */
	public boolean isTimeToSync()
	{
		return System.currentTimeMillis() - receiveTime > Constants.timeToSync*1000 ; 
	}
	
    @Override
    public PreparedStatement getPreparedStatement(Connection conn) throws SQLException
    {
        String sql = "insert into " + TableMeta.table_message +
        " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        return conn.prepareStatement(sql) ;
    }
    
    public byte[] getContent()
    {
        return content;
    }
    public void setContent(byte[] content)
    {
        this.content = content;
    }
    public String getContentType()
    {
        return contentType;
    }
    public void setContentType(String contentType)
    {
        this.contentType = contentType;
    }
//    /**
//     * 该消息已经应答过了
//     * 
//     * */
//	public boolean isResponsed() 
//	{
//		return (status == MessageStatus.RESPONSED.status) ;
//	}
	
//	public void setResponsed()
//	{
//		setStatus(MessageStatus.RESPONSED.status) ;
//		if (responseTime == 0)
//			responseTime = System.currentTimeMillis() ;
//	}
    public void setProcessing()
    {
    	setStatus(MessageStatus.PROCESSING.status) ;
    }
	public static MessageBean toMessageBean(ResultSet rs) 
	{
		MessageBean message = new MessageBean() ;
		try 
		{
			message.setAccountId(rs.getLong(TableMeta.column_account_id)) ;
			message.setAnswer(rs.getString(TableMeta.column_answer)) ;
			message.setAnswerTime(rs.getLong(TableMeta.column_answer_time)) ;
			message.setClientId(rs.getLong(TableMeta.column_client_id)) ;
			java.sql.Blob content = rs.getBlob(TableMeta.column_content) ;
			message.setContent(content==null?null:content.getBytes(1L, (int)content.length())) ;
			message.setContentType(rs.getString(TableMeta.column_content_type)) ;
			message.setGameType(rs.getInt(TableMeta.column_game_type)) ;
			message.setId(rs.getLong(TableMeta.column_msg_id)) ;
			message.setInterval(rs.getInt(TableMeta.column_interval)) ;
			message.setIp(rs.getString(TableMeta.column_ip)) ;
			message.setPort(rs.getInt(TableMeta.column_port)) ;
			message.setReceiveTime(rs.getLong(TableMeta.column_receive_time)) ;
			message.setRelativePath(rs.getString(TableMeta.column_relative_path)) ;
			message.setRequestTime(rs.getLong(TableMeta.column_request_time)) ;
			message.setStatus(rs.getInt(TableMeta.column_status)) ;
			message.setUserId(rs.getLong(TableMeta.column_user_id)) ;
			message.setUPoint(rs.getInt(TableMeta.column_point)) ;
			message.setReturnUserId(rs.getLong(TableMeta.column_return_user_id)) ;

		}
		catch (SQLException e) 
		{
			e.printStackTrace();
			return null ;
		}
		
		return message;
	}
	/**
	 * 错题或者超时状态
	 * 
	 * */
	public boolean isReported()
	{
		return this.status == MessageStatus.WRONG.status 
			||this.status == MessageStatus.TIME_OUT.status ; 
	}
	public void setDeleted()
	{
	}
	public boolean isDeleted()
	{
		return false ;
	}
	public Long getUserId() {
		return userId;
	}
	public void setUserId(Long userId) {
		this.userId = userId;
	}
	public int getUPoint() {
		return uPoint;
	}
	public void setUPoint(int point) {
		this.uPoint = point;
	}
	public long getReturnUserId() {
		return returnUserId;
	}
	public void setReturnUserId(long returnUserId) {
		this.returnUserId = returnUserId;
	}
}
